package com.example.hao.huanxin;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;


import com.hyphenate.EMCallBack;
import com.hyphenate.EMConnectionListener;
import com.hyphenate.EMError;
import com.hyphenate.EMMessageListener;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.exceptions.HyphenateException;
import com.hyphenate.util.NetUtils;

import java.util.List;

public class MainActivity extends AppCompatActivity {

    public final String TAG = this.getClass().getSimpleName();
    private MyConnectionListener listener;
    private EMMessageListener msgListener;
    private EditText et_message;
    private EditText et_nick;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initView();

        //注册一个监听连接状态的listener
        listener = new MyConnectionListener();
        EMClient.getInstance().addConnectionListener(listener);

        listenerMessage();
    }

    private void initView() {
        et_message = findViewById(R.id.et_message);
        et_nick = findViewById(R.id.et_nick);
    }

    public void sendMsg(View view) {
        String msg = et_message.getText().toString();
        String nick = et_nick.getText().toString();

        //创建一条文本消息，content为消息文字内容，toChatUsername为对方用户或者群聊的id，后文皆是如此
        EMMessage message = EMMessage.createTxtSendMessage(msg, nick);
//如果是群聊，设置chattype，默认是单聊
//        if (chatType == CHATTYPE_GROUP)
//            message.setChatType(ChatType.GroupChat);
//发送消息
        EMClient.getInstance().chatManager().sendMessage(message);
    }

    private void listenerMessage() {
        //收到消息
        //收到透传消息
        //收到已读回执
        //收到已送达回执
        //消息被撤回
        //消息状态变动
        msgListener = new EMMessageListener() {

            @Override
            public void onMessageReceived(List<EMMessage> messages) {
                //收到消息
                Log.d(TAG, "onMessageReceived: " + messages);
                Log.i(TAG, "onMessageReceived: " + Thread.currentThread().getName());
            }

            @Override
            public void onCmdMessageReceived(List<EMMessage> messages) {
                //收到透传消息
                Log.d(TAG, "onCmdMessageReceived: " + messages);
            }

            @Override
            public void onMessageRead(List<EMMessage> messages) {
                //收到已读回执
                Log.d(TAG, "onMessageRead: " + messages);
            }

            @Override
            public void onMessageDelivered(List<EMMessage> message) {
                //收到已送达回执
                Log.d(TAG, "onMessageDelivered: " + message);
            }


            @Override
            public void onMessageChanged(EMMessage message, Object change) {
                //消息状态变动
                Log.d(TAG, "onMessageChanged: " + message);
            }
        };
        EMClient.getInstance().chatManager().addMessageListener(msgListener);
//        记得在不需要的时候移除listener，如在activity的onDestroy()时

    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        EMClient.getInstance().removeConnectionListener(listener);
        EMClient.getInstance().chatManager().removeMessageListener(msgListener);
    }

    public void register(View view) {
        //注册失败会抛出HyphenateException
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    EMClient.getInstance().createAccount("geoffrey", "123456");//同步方法
                    Log.d(TAG, "run: 注册成功!");
                } catch (HyphenateException e) {
                    Log.e(TAG, "register: " + e.getMessage());
                    e.printStackTrace();
                }
            }
        }).start();

    }

    public void login(View view) {
        EMClient.getInstance().login("geoffrey", "123456", new EMCallBack() {//回调
            @Override
            public void onSuccess() {
                EMClient.getInstance().groupManager().loadAllGroups();
                EMClient.getInstance().chatManager().loadAllConversations();
                Log.d(TAG, "登录聊天服务器成功！");
//                Log.i(TAG, "onSuccess: " + Thread.currentThread().getName());
            }

            @Override
            public void onProgress(int progress, String status) {

            }

            @Override
            public void onError(int code, String message) {
                Log.d(TAG, "登录聊天服务器失败！");
            }
        });
    }

    public void exit(View view) {
        EMClient.getInstance().logout(true, new EMCallBack() {

            @Override
            public void onSuccess() {
                // TODO Auto-generated method stub
                Log.i(TAG, "onSuccess: 退出登录成功!");
            }

            @Override
            public void onProgress(int progress, String status) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onError(int code, String message) {
                // TODO Auto-generated method stub
                Log.e(TAG, "onError: " + message);

            }
        });
    }


    //实现ConnectionListener接口
    private class MyConnectionListener implements EMConnectionListener {
        @Override
        public void onConnected() {
            Log.d(TAG, "onConnected: ");
        }

        @Override
        public void onDisconnected(final int error) {
            runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    if (error == EMError.USER_REMOVED) {
                        // 显示帐号已经被移除
                        Log.i(TAG, "run: 帐号已经被移除");
                    } else if (error == EMError.USER_LOGIN_ANOTHER_DEVICE) {
                        // 显示帐号在其他设备登录
                        Log.i(TAG, "run: 帐号在其他设备登录");
                    } else {
                        if (NetUtils.hasNetwork(MainActivity.this)) {
                            //连接不到聊天服务器
                        } else {
                            //当前网络不可用，请检查网络设置
                        }
                    }
                }
            });
        }
    }
}


